from flask import jsonify, make_response, request, g
from flask_restful import Resource

from apps.model.serializeModel import model_to_list
from apps.settingApi.api.timerTask.model import timerTaskConfigModel, timerTaskModel, timerTaskLogModel
from apps.settingApi.api.timerTask.utils import  getList as utilsGetList, controllerPostPk,getPk as utilsGetPk
from apps.settingApi.switchCase.serializeParameter import serializeGetFilter, pageResultData
from apps.settingApi.switchCase.settingCurd import getList
from comm.dbConnect import dbListJon

from comm.decorator import login_required
from comm.sqlalchemyConfig import db
timerTaskViewModel = timerTaskModel


class timerTaskListView(Resource):
    # 查询用户列表
    @login_required()
    def get(self):
        # 获取所有的参数
        args = request.args
        objData ,err = utilsGetList(args)
        if err!=None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功','result': objData}), 200)

    @login_required()
    def post(self):
        args = request.get_json()
        if args is None:
            return make_response(jsonify({'msg': '请提供参数'}), 202)
        pkList = args.get('pkList',[])
        isSta = args.get('isSta',None)
        if isSta == None:
            return make_response(jsonify({'msg': '参数错误'}), 202)
        status_z = True
        if isSta != True:
            status_z = False
        # aa = db.session.query(timerTaskViewModel).filter(timerTaskViewModel.id.in_(pkList)).all()
        # print(len(aa))
        db.session.query(timerTaskViewModel).filter(timerTaskViewModel.id.in_(pkList)).update({'status':status_z})
        db.session.commit()
        return make_response(jsonify({'msg': '成功', 'result': {}}), 200)



class timerTaskPkView(Resource):
    @login_required()
    def get(self, pk):
        objData = utilsGetPk(pk)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)
    def post(self,pk):
        data = db.session.query(timerTaskViewModel).filter(timerTaskViewModel.id == pk).first()
        if data.status==True:
            status_z = False
        else:
            status_z = True
        db.session.query(timerTaskViewModel).filter(timerTaskViewModel.id == pk).update({'status': status_z})
        db.session.commit()
        return make_response(jsonify({'msg': '成功', 'result': {}}), 200)


class timerTaskLogsListView(Resource):
    @login_required()
    def get(self):
        # # 获取所有的参数
        # args = request.args
        # objData, err = getList(timerTaskLogModel, args)
        # if err != None:
        #     return make_response(jsonify({'msg': err}), 202)
        # return make_response(jsonify({'msg': '成功', 'result': objData}), 200)
        # 获取所有的参数
        args_z = request.args
        argsData = {}
        for itm in args_z.keys():
            argsData[itm] = args_z[itm]
        if 'status' in args_z.keys():
            if argsData['status'] == 'false':
                argsData['status'] = False
            if argsData['status'] == 'true':
                argsData['status'] = True
        print(argsData)
        serializeFilterList, args = serializeGetFilter(timerTaskLogModel,argsData)
        print(serializeFilterList)
        print(args)
        modelDataObj = timerTaskLogModel.query.filter(*serializeFilterList).order_by(
            timerTaskLogModel.id.desc()).paginate(page=args['page'], per_page=args['pageSize'], error_out=False)
        objData = pageResultData(modelDataObj)
        result = model_to_list(modelDataObj, [])
        objData["data"] = result  # 分页数据
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    def put(self):
        sql1 = """
select c.rem as task_rem, a.id,a.name,a.[order],a.data,a.status,a.is_c,CONVERT(VARCHAR(20), a.create_time, 120) as create_time, CONVERT(VARCHAR(20), a.update_time, 120) as update_time,a.rem
 from tx_timer_task_log a
inner join (
select name,[order], max(id) as id from tx_timer_task_log where status=0 and is_c=0 group by name,[order]) b on a.id=b.id
inner join (
select name,[order], max(id) as id from tx_timer_task_log group by name,[order]) b1 on a.id=b1.id
inner join tx_timer_task c on a.name=c.name
where b.id=b1.id
        """
        data, err = dbListJon(sql1)
        if err != None:
            return make_response(jsonify({'msg': '查询失败'}), 202)
        return make_response(jsonify({'msg': '成功', 'result': data}), 200)
class timerTaskConfigListView(Resource):
    @login_required()
    def get(self):
        data = timerTaskConfigModel.getPk()
        return make_response(jsonify({'msg': '成功', 'result': data}), 200)

    @login_required()
    def post(self):
        # 获取所有参数
        if request.is_json == True:
            args = request.get_json()
        else:
            args = request.form
        if len(args) == 0:
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        argsData = {}
        time_z = args.get('time',None)
        status = args.get('status',None)
        if time_z !=None or time_z!='':
            argsData['time'] = time_z
        if status !=None or status!='':
            argsData['status'] = status
            if type(status)!=bool:
                return make_response(jsonify({'msg': '参数异常'}), 202)
        db.session.query(timerTaskConfigModel).filter().update(argsData)
        db.session.commit()
        # 判断是否需要启动定时任务
        controllerPostPk()
        return make_response(jsonify({'msg': '成功', 'result': {}}), 200)

class timerTaskLogsPkView(Resource):
    def put(self,pk):
        firstData = db.session.query(timerTaskLogModel).filter(timerTaskLogModel.id == pk).first()
        if firstData == None:
            return make_response(jsonify({'msg': '数据被抢先修改请刷新'}), 202)
        db.session.query(timerTaskLogModel).filter(timerTaskLogModel.name==firstData.name).update({"is_c":True})
        db.session.commit()
        return make_response(jsonify({'msg': '成功', 'result': {}}), 200)